// Copyright DustedPixels.com 2008. All rights reserved.

package com.dustedpixels.common.base;

import java.util.Collection;
import java.util.concurrent.atomic.AtomicReference;

/**
 * Utility static methods working on {@code Receiver}.
 * 
 * @author micapolos@gmail.com (Michal Pociecha-Los)
 */
public final class Receivers {
  /**
   * Returns a receiver which will set accepted object on given {@code Reference}.
   * 
   * @param <T> type of accepted object
   * @param reference underlying reference
   * @return a receiver
   */
  public static <T> Receiver<T> set(final Reference<? super T> reference) {
    return new Receiver<T>() {
      public void accept(T object) {
        reference.set(object);
      }
    };
  }

  /**
   * Returns a receiver which will set accepted object on given 
   * {@code AtomicReference}.
   * 
   * @param <T> type of accepted object
   * @param reference underlying reference
   * @return a receiver
   */
  public static <T> Receiver<T> set(final AtomicReference<? super T> reference) {
    return new Receiver<T>() {
      public void accept(T object) {
        reference.set(object);
      }
    };
  }

  /**
   * Returns a receiver which will collect accepted object into underlying
   * collection. Every call to {@code accept} method causes {@code add} method
   * to be called on the collection.
   * 
   * @param <T> type of accepted object
   * @param collection underlying collection
   * @return a receiver
   */
  public static <T> Receiver<T> add(final Collection<? super T> collection) {
    return new Receiver<T>() {
      public void accept(T object) {
        collection.add(object);
      }
    };
  }
}
